package cn.zqh.brand.service.impl;

import cn.zqh.bean.api.CommonResult;
import cn.zqh.bean.api.ResultCode;
import cn.zqh.bean.bo.*;
import cn.zqh.brand.client.CommodityClient;
import cn.zqh.brand.client.StoreClient;
import cn.zqh.brand.client.UserClient;
import cn.zqh.brand.config.BSException;
import cn.zqh.brand.holder.LoginUserHolder;
import cn.zqh.brand.mapper.BrandMapper;
import cn.zqh.brand.mapper.OrderMapper;
import cn.zqh.brand.mapper.ShopCarMapper;
import cn.zqh.brand.service.OrderService;
import cn.zqh.uuid.utils.SnowflakeId;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zqh
 * @since 2023-03-01
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Dydj> implements OrderService {


    @Resource
    private OrderMapper orderMapper;

    @Resource
    private CommodityClient commodityClient;

    @Resource
    private UserClient userClient;

    @Resource
    private LoginUserHolder loginUserHolder;

    @Resource
    private BrandMapper brandMapper;

    @Resource
    private ShopCarMapper shopCarMapper;

    @Resource
    private StoreClient storeClient;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private RestTemplate restTemplate;



    /**
      * @Author: zqh
      * @Date:
      * @Description: 商品购买(添加订单)
    */
//    @SneakyThrows
    @Override
    public CommonResult buyACommodity(String commodityId, Integer number) {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        if (currentUser == null) {
            throw new BSException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        //查询购买商品信息
        CommonResult forObject = restTemplate.getForObject("http://127.0.0.1:9801/commodity/getfoodsById?id=" + commodityId, CommonResult.class);
        String s = JSON.toJSONString(forObject.getData());
        Commodity commodity = JSON.parseObject(s, Commodity.class);
        System.out.println(commodity);
        //查询购买者信息
        CommonResult forUser = restTemplate.getForObject("http://127.0.0.1:9501/user/getUserById?userId=" + currentUser.getId(), CommonResult.class);
        String s1 = JSON.toJSONString(forUser.getData());
        User user = JSON.parseObject(s1, User.class);
        System.out.println(user);
        //看用户钱是否足够
        if (user.getHavaMoney() < commodity.getPrice() * number){
            return CommonResult.failed("余额不足");
        }
        //看购买量是否大于库存量
        if (number > commodity.getNumber()){
            return CommonResult.failed(" 库存不足");
        }
        //购买者钱减少
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userId",user.getUserId());
        hashMap.put("money", commodity.getPrice()*number);
        String remoney = JSON.toJSONString(hashMap);
        rabbitTemplate.convertAndSend("ms6","",remoney);
        //商品库存量减少
        Brand brand = brandMapper.selectOne(new QueryWrapper<Brand>().eq("Brand_id", commodity.getBrandId()));
        HashMap<String, Object> hashMap1 = new HashMap<>();
        hashMap1.put("commodityId",commodity.getCommodityId());
        hashMap1.put("number", number);
        String reNumber = JSON.toJSONString(hashMap1);
        rabbitTemplate.convertAndSend("ms7","",reNumber);
        //增加一个订单
//        Commodity commodity1 = commodityClient.gCommodity(commodityId);
        Dydj order = new Dydj();
        order.setOrderId("order"+ SnowflakeId.nextId())
                .setUserId(user.getUserId())
                .setStoreId(commodity.getStoreId())
                .setCommodityId(commodityId)
                .setNumber(number)
                .setPrice(number * commodity.getPrice())
                .setAddress(user.getAddress())
                .setIsDelete(0)
                .setStyle(1);

        int i = orderMapper.insert(order);
        if (i != 1){
            return CommonResult.failed();
        }
        System.out.println("666666666666666");

        //店主钱增加
        HashMap<String, Object> hashMap2 = new HashMap<>();
        hashMap2.put("money",commodity.getPrice() * number);
        String addMoney = JSON.toJSONString(hashMap2);
        rabbitTemplate.convertAndSend("ms8","",addMoney);
        return CommonResult.success(ResultCode.SUCCESS);
    }
    
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 把购物车里的商品提交订单
    */
    @Override
    public CommonResult submitTheorderForCart(String shopCarId) {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        CommonResult forUser = restTemplate.getForObject("http://127.0.0.1:9501/user/getUserById?userId=" + currentUser.getId(), CommonResult.class);
        String suerString = JSON.toJSONString(forUser.getData());
        User user = JSON.parseObject(suerString, User.class);
        //删除购物车中信息
        ShopCar shopCar = shopCarMapper.selectById(shopCarId);
        //查询购买商品信息
        CommonResult forObject = restTemplate.getForObject("http://127.0.0.1:9801/commodity/getfoodsById?id=" + shopCar.getCommodityId(), CommonResult.class);
        String commoditySting = JSON.toJSONString(forObject.getData());
        Commodity commodity1 = JSON.parseObject(commoditySting, Commodity.class);
        CommonResult forObject1 = restTemplate.getForObject("http://127.0.0.1:9801/commodity/getCommodityById?id=" + shopCar.getCommodityId(), CommonResult.class);
        String s1 = JSON.toJSONString(forObject1.getData());
        EsCommodity commodity = JSON.parseObject(s1, EsCommodity.class);
        //购买商品库存减少
        HashMap<String, Object> hashMap1 = new HashMap<>();
        hashMap1.put("commodityId",commodity.getCommodityId());
        hashMap1.put("number", shopCar.getNumber());
        String reNumber = JSON.toJSONString(hashMap1);
        rabbitTemplate.convertAndSend("ms7","",reNumber);
        //店主钱增加
        CommonResult result = restTemplate.getForObject("http://127.0.0.1:9601/store/getStoreInformationByStoreId?storeId=" + commodity1.getStoreId(), CommonResult.class);
        if (result.getCode() != 200){
            return CommonResult.failed();
        }
        String s2 = JSON.toJSONString(result);
        Store store = JSON.parseObject(s2, Store.class);
        CommonResult forUser2 = restTemplate.getForObject("http://127.0.0.1:9501/user/getUserById?userId=" + store.getUserId(), CommonResult.class);
        String s3 = JSON.toJSONString(forUser2.getData());
        User user1 = JSON.parseObject(s3, User.class);
        HashMap<String, Object> hashMap2 = new HashMap<>();
        hashMap2.put("money",user1.getHavaMoney() + shopCar.getMoney());
        String addMoney = JSON.toJSONString(hashMap2);
        rabbitTemplate.convertAndSend("ms8","",addMoney);
        //创建新订单
        Dydj order = new Dydj();
        order.setOrderId("order"+SnowflakeId.nextId())
                .setUserId(user.getUserId())
                .setStoreId(commodity1.getStoreId())
                .setCommodityId(commodity.getCommodityId())
                .setAddress(user.getAddress())
                .setNumber(shopCar.getNumber())
                .setPrice(shopCar.getMoney())
                .setIsDelete(0)
                .setStyle(1);
        int i = orderMapper.insert(order);
        if (i != 1){
            return CommonResult.failed();
        }
        //删除该用户购物车中该商品
        shopCarMapper.deleteById(shopCarId);

        return CommonResult.success(ResultCode.SUCCESS);
    }
    
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 用户查询自己的订单
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult usersQueryTheirOrders(Integer page, Integer size) {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        page = (page = 1) * size;
        List<Dydj> orders = orderMapper.userGetOwnOrders(currentUser.getId(),page, size);
        return CommonResult.success(orders);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 用户查询自己订单的数量
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult userGetOrdersNum() {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        Integer number = orderMapper.getUserOrderNumber(currentUser.getId());
        return CommonResult.success(number);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 店主获取店铺所有订单的数量
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult storerGetOrdersNum() {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        Store store = storeClient.QueryTheStoresUnderTheCompanyThroughTheUserPrimaryKey(currentUser.getId());
        Integer number = orderMapper.getStorerOrderNumber(store.getStoreId());
        return CommonResult.success(number);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 店主分页查询自己订单
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult storerGetOrdersByPage(Integer page, Integer size) {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        Store store = storeClient.QueryTheStoresUnderTheCompanyThroughTheUserPrimaryKey(currentUser.getId());
        List<Dydj> orders = orderMapper.storerGetOwnOrders(store.getStoreId(), (page - 1) * size, size);
        return CommonResult.success(orders);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 管理员获取所有订单数量
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult adminGetAllOrderNum() {
        Integer number = orderMapper.getAllOrdersNumber();
        return CommonResult.success(number);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 管理员分页获取所有订单
    */
    @Override
    public CommonResult adminGetAllOrdersByPage(Integer page, Integer size) {
//        ArrayList<Object> list = new ArrayList<>();
        List<Dydj> orders = orderMapper.adminGetAllOrders((page - 1) * size, size);
//        for (Dydj order : orders) {
//            HashMap<String, Object> hashMap = new HashMap<>();
//            User user = userClient.getUserById(order.getUserId());
//            EsCommodity esCommodity = commodityClient.getCommodityById(order.getCommodityId());
//            hashMap.put("order",order);
//            hashMap.put("user",user);
//            hashMap.put("commodity",esCommodity);
//            list.add(hashMap);
//        }
        return CommonResult.success(orders);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 修改订单状态
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult updaTheOrderStyle(String orderId, Integer sty) {
        Dydj order = orderMapper.selectById(orderId);
        order.setStyle(sty);
        int i = orderMapper.updateById(order);
        if (i != 1){
            return CommonResult.failed();
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 用户取消订单
    */
    @SneakyThrows
    @Override

    public CommonResult userCancelsTheOrder(String orderId) {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        Dydj order = orderMapper.selectById(orderId);
        if (!currentUser.getId().equals(order.getUserId())){
            return CommonResult.failed(ResultCode.VALIDATE_FAILED.getMessage());
        }
        if (order.getStyle() != 1){
            return CommonResult.failed("商家已发货，现阶段不支持退货");
        }
        User user = userClient.getUserById(currentUser.getId());
        AdminChangeUserInfo adminChangeUserInfo = new AdminChangeUserInfo();
        adminChangeUserInfo.setId(user.getUserId())
                .setEmail(user.getQqEmail())
                .setName(user.getNickName())
                .setSex(user.getSex())
                .setAvatar(user.getAvatar())
                .setIntro(user.getIntro())
                .setAddress(user.getAddress())
                .setIsStore(user.getIsStore())
                .setMoney(user.getHavaMoney() + order.getPrice())
                .setIsDelete(user.getIsDelete());

        String commonResult = userClient.adminChangeInfo(adminChangeUserInfo);
        if (!"SUCCESS".equals(commonResult) ) {
            return CommonResult.failed();
        }
        EsCommodity commodity = commodityClient.getCommodityById(order.getCommodityId());
        Brand brand = brandMapper.selectOne(new QueryWrapper<Brand>().eq("Brand_name", commodity.getBrandName()));
        AdminChangeCommodity adminChangeCommodity = new AdminChangeCommodity();
        adminChangeCommodity.setCommodityId(commodity.getCommodityId())
                .setCommodityName(commodity.getCommodityName())
                .setAvatar(commodity.getAvatar())
                .setIntro(commodity.getIntro())
                .setStyle(commodity.getStyleName())
                .setPrice(commodity.getPrice())
                .setNumber(commodity.getNumber() + order.getNumber())
                .setSalesVolume(commodity.getSalesVolume())
                .setBrandId(brand.getBrandId());

        String commonResult1 = commodityClient.ModifyTheProductInformationBasedOnTheAdministrator(adminChangeCommodity);
        if (!"SUCCESS".equals(commonResult1)) {
            return CommonResult.failed();
        }

        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 订单删除
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult delOrderById(String orderId) {
        Dydj order = orderMapper.selectById(orderId);
        if (order.getStyle() != 3){
            return CommonResult.failed("商品还未收货，现在不能进行删除操作");
        }
        int i = orderMapper.deleteById(orderId);
        if (i != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 管理员获取被删除了的订单
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult adminGelDelOrdersByPage(Integer page, Integer size) {
        List<Dydj> orders = orderMapper.adminGetDelOrders((page - 1) * size, size);
        return CommonResult.success(orders);
    }


}
